package vip.ola.pay.channel.unizfb;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import vip.ola.core.common.constant.PayConstant;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.common.util.PayDigestUtil;
import vip.ola.core.common.util.PayUtil;
import vip.ola.core.entity.PayOrder;
import vip.ola.core.entity.PayPassageAccount;
import vip.ola.pay.channel.BasePayment;
import vip.ola.pay.channel.abc.AbcPaymentService;
import vip.ola.pay.channel.uniwx.UniwxPaymentService;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Base64;

import static vip.ola.core.common.constant.Constant.UTF8;
import static vip.ola.core.common.constant.PayEnum.ERR_0010;
import static vip.ola.core.common.constant.PayEnum.ERR_0121;

@Service
public class UnizfbPaymentService extends BasePayment {

    private static final MyLog _log = MyLog.getLog(AbcPaymentService.class);

    @Override
    public String getChannelName() {
        return PayConstant.CHANNEL_NAME_CODE;
    }

    @Override
    public JSONObject pay(PayOrder payOrder) {
        try {
            System.out.println("话费支付使用子账号ID：" + payOrder.getChannelMchId());
            PayPassageAccount payPassageAccount = rpcCommonService.rpcPayPassageAccountService.findById(payOrder.getPassageAccountId());
            if (payPassageAccount == null || StringUtils.isBlank(payPassageAccount.getParam())) {
                return PayUtil.makeRetFail(ERR_0121);
            }
            JSONObject accountParams = JSONObject.parseObject(payPassageAccount.getParam());

            String uid = payPassageAccount.getPassageMchId();
            Long amount = new BigDecimal(payOrder.getAmount()).divide(new BigDecimal(100)).longValue();
            String orderId = payOrder.getPayOrderId();
            String reqUrl = accountParams.getString("reqUrl");
            StringBuilder sb = new StringBuilder();
            sb.append(reqUrl).append("?").append("uid=").append(uid).append("&order=").append(orderId);
            sb.append("&money=").append(amount).append("&sign=").append(UniwxPaymentService.getSignByPay(uid,amount.toString(),payPassageAccount.getPrivateKey()));
            //这里是外部拉单服务器，
            String payUrl = Base64.getEncoder().encodeToString(sb.toString().getBytes());
            String[] domains = accountParams.getString("orderUrl").split(",");
            int index = (int) (Math.random() * domains.length);
            String domian = domains[index];
            String getOrderUrl = "http://" + domian + "/get.php?url=" + payUrl + "&orderId=" + orderId + "&amount=" + amount + "&returnUrl=" + URLEncoder.encode(payOrder.getReturnUrl(),"UTF-8");
            _log.info("最终拉单连接:" + getOrderUrl);
            int result = rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
            _log.info("更新订单状态为支付中: result={}", result);
            return PayUtil.makeRetPayUrl(getOrderUrl, null);
        }catch (Exception e){
            _log.error(e, "调用话费渠道异常。");
            return PayUtil.makeRetFail(ERR_0010);
        }
    }

    @Override
    public JSONObject query(PayOrder payOrder) {
        return null;
    }

    /**
     * 计算通知的sign
     * @param uid
     * @param id
     * @param state
     * @param signKey
     * @return
     */
    public static String getSignByNotify(String uid, String id, String state, String signKey){
        return PayDigestUtil.md5(uid + id + state + signKey, UTF8);
    }

    /**
     * 计算发起支付的sign
     * @param uid
     * @param amount
     * @param signKey
     * @return
     */
    public static String getSignByPay(String uid, String amount, String signKey){
        return PayDigestUtil.md5(uid+amount+signKey,UTF8);
    }
}
